#include "Player.h"

#include <QTcpSocket>
#include <QStringList>

Player::Player(){
    player_id = -1;
    phase = Inactive;
    is_hosted = false;
}

int Player::getPlayerId() const{
    return player_id;
}

void Player::setPlayerId(int id){
    player_id = id;
}

QString Player::getPlayerName() const{
    return player_name;
}

void Player::setPlayerName(const QString &name){
    player_name = name;
}

Player::Phase Player::getPhase() const{
    return phase;
}

void Player::setPhase(Phase phase){
    this->phase = phase;
}

QString Player::getPhaseString() const{
    switch(phase){
    case Start:
        return "start";
    case Playing:
        return "playing";
    case End:
        return "end";
    case Inactive:
        return "inactive";
    }

    return NULL;
}

void Player::setPhaseString(const QString &phase_str){
    if(phase_str == "start"){
        phase = Start;
    }else if(phase_str == "playing"){
        phase = Playing;
    }else if(phase_str == "end"){
        phase = End;
    }else if(phase_str == "inactive"){
        phase = Inactive;
    }
}

bool Player::isReady() const{
    return is_ready;
}

void Player::setReady(bool ready){
    is_ready = ready;
}

bool Player::isHosted() const{
    return is_hosted;
}

void Player::setHosted(bool hosted){
    is_hosted = hosted;
}

void Player::fromString(const QString &str){
    QStringList l = str.split(' ');
    if(l.length() >= 2){
        player_id = l.at(0).toInt();
        player_name = l.at(1);
    }
}

QString Player::toString() const{
    return QString("%1 %2").arg(player_id).arg(player_name);
}

void Player::notify(CommandType command, const QByteArray &data){
    static char command_str[2] = {0};
    command_str[0] = '0' + (char) command;

    qDebug() << objectName() << "Sending command =" << command_str;

    socket->write(command_str);
    socket->write("=");
    socket->write(data.toBase64());
    socket->write("\n");
}

void Player::notify(CommandType command, const QString &data){
    notify(command, data.toUtf8());
}

void Player::notify(CommandType command){
    static char command_str[2] = {0};
    command_str[0] = '0' + (char) command;

    qDebug() << objectName() << "Sending command =" << command_str;

    socket->write(command_str);
    socket->write("=");
    socket->write("\n");
}

void Player::notifyProperty(const char *key){
    notify(SetProperty, QString("%1 %2").arg(key).arg(property(key).toString()));
}
